package com.rao.travel.dao;

import com.rao.travel.pojo.Permission;
import com.rao.travel.pojo.Role;
import org.apache.ibatis.annotations.*;

import java.util.List;

/**
 * @author Srao
 * @version 1.0
 * @className RoleDao
 * @date 2019/10/31 19:37
 * @package com.rao.travel.dao
 * @description
 */
@Mapper
public interface RoleDao {

    /*根据用户id查询角色，并查询出权限*/
    @Select("select * from role where id in (select roleId from users_role where userId = #{userId})")
    @Results({
            @Result(id = true, property = "id", column = "id"),
            @Result(property = "roleName", column = "roleName"),
            @Result(property = "roleDesc", column = "roleDesc"),
            @Result(property = "permissions", column = "id", javaType = java.util.List.class, many = @Many(select = "com.rao.travel.dao.PermissionDao.findByRoleId"))
    })
    List<Role> findByUserId(String userId);

    /*查询所有角色*/
    @Select("select * from role")
    List<Role> findAll();

    /*保存角色*/
    @Insert("insert into role(roleName, roleDesc) values (#{roleName}, #{roleDesc})")
    void save(Role role);

    /*查询角色详情*/
    @Select("select * from role where id = #{id}")
    @Results({
            @Result(column = "id", property = "id", id = true),
            @Result(column = "roleName", property = "roleName"),
            @Result(column = "roleDesc", property = "roleDesc"),
            @Result(column = "id", property = "permissions", javaType = java.util.List.class, many = @Many(select = "com.rao.travel.dao.PermissionDao.findByRoleId"))
    })
    Role findById(String id);

    /*从users_role中删除*/
    @Delete("delete from users_role where roleId = #{id}")
    void deleteFromUsersRole(String id);

    /*从role_permission中删除*/
    @Delete("delete from role_permission where roleId = #{id}")
    void deleteFromRolePermission(String id);

    /*从role中删除*/
    @Delete("delete from role where id = #{id}")
    void deleteFromRole(String id);

    /*查询该角色还未拥有的权限*/
    @Select("select * from permission where id not in (select permissionId from role_permission where roleId = #{id})")
    List<Permission> findOtherPermission(String id);

    /*为角色添加权限*/
    @Insert("insert into role_permission(permissionId, roleId) values (#{permissionId}, #{roleId})")
    void addPermissionToRole(@Param(value = "permissionId") String permissionId, @Param(value = "roleId") String roleId);
}
